import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/address_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BlankToolBarTool.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:panda/util/my_citypicker.dart';
import '../base/Constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/**
 * 添加收货地址
 * 2019-8-27
 */
class AddAddressPage extends StatefulWidget {
  AddressListDataData item;
  AddAddressPage({Key key, this.item}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new AddAddressView();
  }
}

class AddAddressView extends State<AddAddressPage> {
  String address = "选择地区";
  String token = "";
  bool _value = false;
  String name = "";
  String phone = "";
  String detail_address = "";
  TextEditingController controller = new TextEditingController();
    BlankToolBarModel barModel = BlankToolBarModel();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
        barModel.outSideCallback = focusNodeChange;

    if (widget.item != null) {
      setState(() {
        address = widget.item.province +
            "-" +
            widget.item.city +
            "-" +
            widget.item.county;
        name = (widget.item.consignee == null ? "" : widget.item.consignee);
        phone = widget.item.contact_number;
        detail_address = widget.item.detail_address;
        _value = (widget.item.is_default == "Y");
      });
    }
    getString(TOKEN).then((value) {
      token = value;
    });
  }
 void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    barModel.removeFocusListeners();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: new AppBar(
        title: new Text(
          widget.item != null ? "编辑地址" : "添加地址",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body:  BlankToolBarTool.blankToolBarWidget(
        context,
        model: barModel,
        body: new Container(
        color: white,
        child: new Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(20)),
              padding: EdgeInsets.only(left: 15, right: 15, bottom: 10),
              decoration: BoxDecoration(
                  color: f0Color,
                  border: Border.all(color: grey, width: 0),
                  borderRadius: BorderRadius.circular(5)),
              child: Column(
                children: <Widget>[
                  new TextField(
                    maxLines: 3,
                    minLines: 3,
                    cursorColor: mainColor,
                    controller: controller,
                    keyboardAppearance: Brightness.light,
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    onChanged: (value) {
                      // auth_code = value;
                    },
                    decoration: new InputDecoration(
                        hintText:
                            "请输入或粘贴地址文本，可自动识别地址姓名和电话，如:江苏省南京市雨花台区软件大道108号，王总，139****7388",
                        border: InputBorder.none,
                        hintStyle: TextStyle(
                            color: Colors.black38,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE))),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      GestureDetector(
                        child: Text(
                          '清除',
                          style: TextStyle(
                              color: Colors.blue,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE + 2)),
                        ),
                        onTap: () {
                          controller.clear();
                        },
                      ),
                      GestureDetector(
                        child: Container(
                          margin: EdgeInsets.only(left: 8),
                          padding: EdgeInsets.fromLTRB(10, 2, 10, 2),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5),
                              color: mainColor),
                          child: Text(
                            '智能解析',
                            style: TextStyle(
                                color: white,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE +2)),
                          ),
                        
                        ),
                        onTap: (){
                          if(controller.text==""){
                            Fluttertoast.showToast(msg: "未识别到内容");
                            return ;
                          }
                          if(controller.text.split(",").length<3&&controller.text.split("，").length<3){
                            Fluttertoast.showToast(msg: "解析失败");
                            return ;
                          }
                          controller.text=controller.text.replaceAll("，", ",");
                          List<String> strs=controller.text.split(',');
                          String address1=strs[0].replaceAll("省", "-").replaceAll("市", "-").replaceAll("区", "-");
                           List<String> strs1=address1.split("-");
                           if(strs1.length<=1){
                             detail_address=address1;
                           }else if(strs1.length==4){
                             address=strs1[0]+"省-"+strs1[1]+"市-"+strs1[2]+"区";
                            detail_address=strs1[3];

                           }
                          name=strs[1];
                          phone=strs[2];
                          setState(() {
                            
                          });
                        },
                      )
                    ],
                  )
                ],
              ),
            ),
            initName(),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            initPhone(),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            initAddress(context),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            initDetail(),
            new Container(
              child: Divider(
                height: 1,
                color: f0Color,
              ),
            ),
            addButton(context)
          ],
        ),
      ),
    ));
  }

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return null;
  }

  Widget initName() {
    return new Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '收货人:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new TextField(
                maxLines: 1,
                cursorColor: mainColor,
                onChanged: (value) {
                  name = value;
                },
                keyboardAppearance: Brightness.light,
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: name == null ? "" : name,
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: name == null ? 0 : name.length)))),
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                decoration: new InputDecoration(
                    hintText: "",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
        ],
      ),
    );
  }

  Widget initPhone() {
    return new Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '联系方式:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new TextField(
                maxLines: 1,
                cursorColor: mainColor,
                onChanged: (value) {
                  phone = value;
                },
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: phone,
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: phone.length)))),
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                decoration: new InputDecoration(
                    hintText: "",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
        ],
      ),
    );
  }

  Widget initDetail() {
    return Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '详细地址:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new TextField(
                maxLines: 2,
                cursorColor: mainColor,
                minLines: 2,
                keyboardAppearance: Brightness.light,
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: detail_address,
                    selection: TextSelection.fromPosition(TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: detail_address.length)))),
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                onChanged: (value) {
                  detail_address = value;
                },
                decoration: new InputDecoration(
                    hintText: "输入详细街道、楼栋号等",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
        ],
      ),
    );
  }

  Widget addButton(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      height: ScreenUtil.getInstance().setHeight(DP_80),
      margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
      decoration: new BoxDecoration(
          color: mainColor, borderRadius: BorderRadius.circular(20.0)),
      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
      child: new FlatButton(
        child: new Padding(
          padding: EdgeInsets.all(0.0),
          child: new Text(
            widget.item != null ? "修改地址" : "确定添加",
            style: new TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          ),
        ),
        onPressed: () {
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (_) {
                return new NetLoadingDialog(
                  loadingText: "保存中...",
                  bgColor: Color.fromARGB(255, 0, 0, 0),
                  requestCallBack: null,
                  outsideDismiss: false,
                );
              });
          addAddress();
        },
      ),
    );
  }

  Widget initAddress(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 0.0),
      color: Colors.white,
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Text(
              '收货地区:',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
            ),
          ),
          new Expanded(
              flex: 3,
              child: new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  showAddressDialog(context);
                },
                child: new Container(
                  padding: EdgeInsets.fromLTRB(0, 15.0, 0, 15.0),
                  child: new Row(
                    children: <Widget>[
                      Expanded(
                        child: new Text(
                          '$address',
                          style: TextStyle(
                              color: address.contains("选择")
                                  ? Colors.black45
                                  : Colors.black87,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.grey,
                        size: 18,
                      )
                    ],
                  ),
                ),
              )),
        ],
      ),
    );
  }

  Future showAddressDialog(BuildContext context) async {
    CityResult result = await showCityPicker(context);
    if (result == null) {
      return;
    }
    setState(() {
      address = result.province + "-" + result.city + "-" + result.county;
    });
  }

  addAddress() async {
    if (name == "") {
      Navigator.of(context).pop(1);

      Fluttertoast.showToast(msg: "请输入收货人");
      return;
    }
    if (phone == "") {
      Navigator.of(context).pop(1);

      Fluttertoast.showToast(msg: "请输入收件人号码");
      return;
    }
    if (address == "") {
      Navigator.of(context).pop(1);

      Fluttertoast.showToast(msg: "请选择收货地区");
      return;
    }
    if (detail_address == "") {
      Navigator.of(context).pop(1);

      Fluttertoast.showToast(msg: "请输入详细街道地址");
      return;
    }
    if (widget.item != null) {
      Map map = new Map();
      map['token'] = token;
      map['id'] = widget.item.id;
      map['province'] = address.split("-")[0];
      map['city'] = address.split("-")[1];
      map['county'] = address.split("-")[2];
      map['detail_address'] = detail_address;
      map['consignee'] = name;
      map['contact_number'] = phone;
      map['is_default'] = _value ? "Y" : "N";
      map['sign_type'] = SignType.EDIT_ADDRESS;
      // print(map);
      Response<String> response =
          await HttpUtil().post(Api.EDIT_ADDRESS, data: getSign(map));
      Map userMap = json.decode(response.data);
      int code = userMap["code"];
      String msg = userMap["msg"];
      Navigator.of(context).pop(1);
      Fluttertoast.showToast(msg: msg);
      // print(userMap['data'].toString());
      if (code == 1 && mounted) {
        Navigator.of(context).pop("1");
      }
      return;
    }
    Map map = new Map();
    map['token'] = token;
    map['province'] = address.split("-")[0];
    map['city'] = address.split("-")[1];
    map['county'] = address.split("-")[2];
    map['detail_address'] = detail_address;
    map['consignee'] = name;
    map['contact_number'] = phone;
    map['is_default'] = _value ? "Y" : "N";
    map['sign_type'] = SignType.ADD_ADDRESS;
    Response<String> response =
        await HttpUtil().post(Api.ADD_ADDRESS, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    // print(userMap['data'].toString());
    if (code == 1) {
      Navigator.of(context).pop("1");
    }
  }
}

class CityResult {
  String province;
  String city;
  String county;
}
